package com.nulldev.util.io.lzma;

import java.io.IOException;
import java.io.OutputStream;

import com.nulldev.util.io.cstreams.CoderOutputStream;
import com.nulldev.util.io.lzma.lzma.Encoder;

public class LZMAOutputStream extends CoderOutputStream {
	public LZMAOutputStream(final OutputStream out, final LZMAEncoderWrapper wrapper) {
        super(out, wrapper);
    }

    public LZMAOutputStream(final OutputStream out, final Encoder lzmaEncoder) {
        this(out, new LZMAEncoderWrapper(lzmaEncoder));
    }

    /**
     * A convenient builder that makes it easier to configure the LZMA encoder.
     * Default values:
     * <ul>
     * <li>dictionnary size: max</li>
     * <li>end marker mode: true</li>
     * <li>match finder: BT4</li>
     * <li>number of fast bytes: 0x20</li>
     * </ul>
     */
    public static class Builder
    {
        private final OutputStream out;

        private int dictionnarySize = 1 << 23;

        private boolean endMarkerMode = true;

        private int matchFinder = Encoder.EMatchFinderTypeBT4;

        private int numFastBytes = 0x20;

        public Builder(OutputStream out)
        {
            this.out = out;
        }

        public Builder useMaximalDictionarySize()
        {
            dictionnarySize = 1 << 28;
            return this;
        }

        public Builder useMediumDictionarySize()
        {
            dictionnarySize = 1 << 15;
            return this;
        }

        public Builder useMinimalDictionarySize()
        {
            dictionnarySize = 1;
            return this;
        }

        public Builder useEndMarkerMode(boolean endMarkerMode)
        {
            this.endMarkerMode = endMarkerMode;
            return this;
        }

        public Builder useBT4MatchFinder()
        {
            matchFinder = Encoder.EMatchFinderTypeBT4;
            return this;
        }

        public Builder useBT2MatchFinder()
        {
            matchFinder = Encoder.EMatchFinderTypeBT2;
            return this;
        }

        public Builder useMinimalFastBytes()
        {
            numFastBytes = 5;
            return this;
        }

        public Builder useMediumFastBytes()
        {
            numFastBytes = 0x20;
            return this;
        }

        public Builder useMaximalFastBytes()
        {
            numFastBytes = 273;
            return this;
        }

        public LZMAOutputStream build() throws IOException
        {
            Encoder encoder = new Encoder();

            encoder.setDictionarySize(dictionnarySize);
            encoder.setEndMarkerMode(endMarkerMode);
            encoder.setMatchFinder(matchFinder);
            encoder.setNumFastBytes(numFastBytes);

            return new LZMAOutputStream(out, encoder);
        }
    }
}
